import { _decorator, Component, EffectAsset, Material, Node, Sprite, Texture2D,gfx } from 'cc';
const { ccclass, property } = _decorator;

const {BlendFactor,CullMode} = gfx;

@ccclass('Example')
export class Example extends Component {

    @property(EffectAsset)
    foo: EffectAsset = null;

    @property(Texture2D)
    dissolveMap:Texture2D = null;

    start() {


        this.normalTest();

        this.scheduleOnce(()=>{
           console.log('howe 修改');
            this.runChange();
        },3)

    }

    normalTest(){

        const sprite = this.getComponent(Sprite);
        const mat = new Material();

        // effect name 适用于内置 shader，可以通过 EffectAsset.get('effect name') 方式获取，判断
        mat.initialize({
            effectAsset : this.foo,
            defines:{
                USE_TEXTURE: true,
            },
            states: {
                blendState:{
                    targets:[
                        {
                            blend: true,
                            blendSrc: BlendFactor.SRC_ALPHA,
                            blendDst: BlendFactor.ONE_MINUS_SRC_ALPHA,
                            blendDstAlpha: BlendFactor.ONE_MINUS_SRC_ALPHA,
                        }

                    ]
                },
                rasterizerState:{
                    cullMode: CullMode.NONE
                }
            }

        });

        sprite.customMaterial = mat;
        mat.setProperty('u_dissolveMap',this.dissolveMap);
        mat.setProperty('dissolveThreshold', 0.3);
    }


    // 如果需要在运行时修改，就可以用下列方式进行动态修改：
    runChange(){
        // 所有带有材质的组件上都可以获取材质，通过 comp.material 获取出来的材质通常都是材质实例 MaterialInstance
        // 材质 Material 和材质实例 MaterialInstance 的区别在于，MaterialInstance 从挂载的那一刻就一直属于唯一的组件，
        // 且只对该组件模型生效，而 Material 则无此限制，可以属于多个同类型组件或者不同类型组件
        // 只有 MaterialInstance 可以运行时动态修改 defines 和 states
        const sprite = this.getComponent(Sprite);
        const mat = new Material();
        mat.initialize({
            effectAsset: this.foo,
        });
        const matInst = sprite.material;

        matInst.recompileShaders({ USE_TEXTURE: true });
        matInst.overridePipelineStates({
            blendState: {
                targets: [
                    {
                        blend: true,
                        blendSrc: BlendFactor.SRC_ALPHA,
                        blendDst: BlendFactor.ONE_MINUS_SRC_ALPHA,
                        blendDstAlpha: BlendFactor.ONE_MINUS_SRC_ALPHA
                    }
                ]
            },
            rasterizerState: {
                cullMode: CullMode.NONE,
            }
        });
        matInst.setProperty('u_dissolveMap', this.dissolveMap!);
        matInst.setProperty('dissolveThreshold', 0.7);
    }

  
}


